package com.shanghaionstar.discover.dealer.service;

import android.content.Context;

import com.onstar.cn.api.DealersService;
import com.onstar.cn.api.UsersService;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;

import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.mvp.base.core.BaseService;
import com.onstar.cn.framework.network.HttpInjectUtils;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.mag.CoordinateEntity;
import com.onstar.cn.mag.dealer.PreferredDealerEntity;
import com.onstar.cn.more.request.DealersQueryRequest;
import com.onstar.cn.more.request.ProcessPreferredDealerRequest;
import com.onstar.cn.more.response.LookupAroundDealerResponse;
import com.shanghaionstar.enumtype.DealerBrandType;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.NetConnectUtil;

import java.util.LinkedHashMap;

import rx.Observable;
import rx.functions.Func0;

/**
 * Created by Rengui Lu on 2016/8/12.
 */
public class PreferDealerService extends BaseService{
    private Context context;

    public PreferDealerService(Context context){
        this.context = context;
    }

    @Override
    public RequestEntity getRequestEntity() {
        return null;
    }

    @Override
    public Object jsonToBean(String json) {
        return null;
    }

//    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
//    public String batchSmartGeoFencingJson(RequestEntity entity) throws OnStarException {
//        UsersService service = new UsersService(
//                Constants.CURRENT_SERVER_URL);
//        Vehicle vehicle = ApplicationUtil.getInstance().getCurrentVehicle();
//        RequestEntity requestEntity = service.batchApplySmartDeviceGeofencing(entity, ApplicationUtil.getInstance().getIdpID(), ApplicationUtil.getInstance().getAccountId(), vehicle == null ? "" : vehicle.getVin());
//        addAuthorization(context, requestEntity);
//        requestEntity = HttpInjectUtils.injectHttp(SmartHomeService.this.getClass(), "batchSmartGeoFencingJson", requestEntity, RequestEntity.class);
//        return BusinessUtil.getResponse(getDatas(requestEntity), context);
//    }
//
    public Observable<PreferredDealerEntity> getPerferDealer() {
        return Observable.defer(new Func0<Observable<PreferredDealerEntity>>() {
            @Override
            public Observable<PreferredDealerEntity> call() {
                try {
                    return Observable.just(GsonHelper.fromJson( getPerferDealerJson(),PreferredDealerEntity.class));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

    // String json =
    // "{\"dealerName\":\"ABC\",\"distance\":0.0,\"cityCode\":\"SH\",\"dealerBrand\":\"BUICK\",\"currentLocation\":{\"longitude\":0.0,\"latitude\":0.0},\"dealerCode\":\"ABC\",\"companyName\":\"安吉星\",\"telephone\":\"58000000\",\"address\":\"田林路3888号新业园0楼\",\"cityName\":\"上海\",\"postcode\":\"200000\",\"province\":\"SH\",\"locationCoordinate\":{\"longitude\":0.0,\"latitude\":0.0},\"directionCoordinate\":{\"longitude\":0.0,\"latitude\":0.0}}";
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.GET)
    public String getPerferDealerJson() throws OnStarException{
        DealersService service = new DealersService(Constants.CURRENT_SERVER_URL);
        RequestEntity entity = NetConnectUtil.getAuthRequestEntity(context);
        PreferredDealerEntity dealerEntity = new PreferredDealerEntity();
        entity = service.getPreferredDealer(entity, ApplicationUtil.getInstance().getIdpID(),
                ApplicationUtil.getInstance().getAccountId(), ApplicationUtil.getInstance().getVin(),dealerEntity);
        entity = HttpInjectUtils.injectHttp(PreferDealerService.this.getClass(), "getPerferDealerJson", entity);
        return BusinessUtil.getResponse(getDatas(entity), context);
    }

    private void addToken(RequestEntity entity) {
        LinkedHashMap<String, Object> coHashMap = new LinkedHashMap<String, Object>();
        coHashMap.put(FinalConstants.HTTP_AUTHORIZATION, ApplicationUtil.getInstance().getToken());
        entity.setCustomHeads(coHashMap);
    }

    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.PUT)
    public String changePerferDealerJson(String partyId) throws OnStarException{
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        ProcessPreferredDealerRequest request = new ProcessPreferredDealerRequest();
        if (partyId != null) {
            request.setPartyID(partyId);
        }
        String subscriberID = ApplicationUtil.getInstance().getIdpID();
        String accountID = ApplicationUtil.getInstance().getAccountId();
        String vin = ApplicationUtil.getInstance().getVin();

        requestEntity = service.getProcessDealer(requestEntity, request, subscriberID, accountID, vin);
        requestEntity = HttpInjectUtils.injectHttp(PreferDealerService.this.getClass(), "changePerferDealerJson", requestEntity,String.class);
        return BusinessUtil.getResponse(getDatas(requestEntity), context);
    }

    public Observable<String> changePerferDealer(final String id) {
        return Observable.defer(new Func0<Observable<String>>() {
            @Override
            public Observable<String> call() {
                try {
                    return Observable.just(changePerferDealerJson(id));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }



    // 加载数据
    @Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO) , method = HttpMethod.PUT)
    public String loadDatasJson(final String cityCode, double latitude, double longitude,int pageNumber,int pageSize) throws OnStarException{
        UsersService service = new UsersService(Constants.CURRENT_SERVER_URL);
        RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
        DealersQueryRequest dealersQueryRequest = new DealersQueryRequest();
        dealersQueryRequest.setCityCode(cityCode); // 城市代码
        dealersQueryRequest.setQueryType("AFTER_SALE"); // 服务类型 ALL / PRE_SALE /
        // AFTER_SALE
        if (ApplicationUtil.getInstance().getCurrentVehicle()!=null) {
            dealersQueryRequest.setDealerBrand(DealerBrandType
                    .getDealerBrandTypeByDesc(ApplicationUtil.getInstance().getCurrentVehicle().getModelDesc()).value()); // 经销商品牌
            dealersQueryRequest.setReturnPreferredDealer("true"); // 是否返回首选经销商
        } else {
            dealersQueryRequest.setDealerBrand("ALL"); // 经销商品牌 ALL / BUICK /
            // CHEVROLET / CADILLAC
            dealersQueryRequest.setReturnPreferredDealer("false"); // 是否返回首选经销商
        }
        CoordinateEntity currentLocation = new CoordinateEntity();
        currentLocation.setLatitude(latitude);
        currentLocation.setLongitude(longitude);
        dealersQueryRequest.setCurrentLocation(currentLocation);
        String subscriberID = ApplicationUtil.getInstance().getSubscriberID();
        String accountID = ApplicationUtil.getInstance().getAccountId();
        String vin = ApplicationUtil.getInstance().getVin();

        requestEntity = service.getCityDealer(requestEntity, dealersQueryRequest, subscriberID, accountID, vin,
                pageNumber, pageSize);
        requestEntity = HttpInjectUtils.injectHttp(PreferDealerService.this.getClass(), "loadDatasJson", requestEntity,
                String.class,double.class, double.class,int.class,int.class);
        return BusinessUtil.getResponse(getDatas(requestEntity), context);

//        Sender sender = new Sender();
//        sender.send(requestEntity, new ResponseHandler() {
//
//            @Override
//            public void onSuccess(String tag, final String json) {
//                logger.e(json);
//                aroundDealerResponse = JsonParseUtil.JsonToBean(LookupAroundDealerResponse.class, json);
//                MyPost.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        try {
//                            JSONObject commandResponse = new JSONObject(json);
//                            JSONArray packageUsageInfo = commandResponse.getJSONArray("dealers");
//                            JSONObject element = (JSONObject) commandResponse.get("pageable");
//                            String pageSize = element.getString("pageSize");
//                            String totalSize = element.getString("totalSize");
//                            Integer pageSizes = Integer.parseInt(pageSize);
//                            Integer totalPages = Integer.parseInt(totalSize);
//
//                            if (!isChange) {
//                                showProgress();
//                                datas_layout.setVisibility(View.VISIBLE);
//                            }
//                            ChangePreferDealerFragment.this.cityCode = aroundDealerResponse.getDealers().get(pageNumber)
//                                    .getCityCode();
//                            if (pageIndex <= 1) {
//                                if (aroundDealer != null) {
//                                    aroundDealer.clear();
//                                }
//                                aroundDealer = JsonParseUtil.JsonToBean(PreferredDealerEntity.class,
//                                        packageUsageInfo.toString());
//                                no_datas.setVisibility(View.GONE);
//                                around_dealer_list.setVisibility(View.VISIBLE);
//                                String cityName = new LoadCityCode(getActivity()).findZhCityByCityCode(cityCode);
//                                current_city.setText(cityName);
//                                if (aroundDealerResponse.getDealers() != null) {
//                                    aroundDealerAdapter = new AroundDealerAdapter(aroundDealerResponse.getDealers(),
//                                            getActivity());
//                                    around_dealer_list.setAdapter(aroundDealerAdapter);
//                                }
//                            } else {
//                                List<PreferredDealerEntity> list = JsonParseUtil.JsonToBean(PreferredDealerEntity.class,
//                                        packageUsageInfo.toString());
//                                if (list != null && list.size() > 0) {
//                                    list.remove(0);
//                                    aroundDealer.addAll(list);
//                                }
//                                no_datas.setVisibility(View.VISIBLE);
//                                around_dealer_list.setVisibility(View.GONE);
//                            }
//                            if (pageSizes < totalPages) { // 是否加载更多
//                                isHasMoreDealer = true;
//                            } else {
//                                isHasMoreDealer = false;
//                            }
////							dismissDialog(dialog);
//                            dismissProgress();
//                            if (isHasMoreDealer) {
//                                more_layout.setVisibility(View.VISIBLE);
//                                tv_more.setVisibility(View.VISIBLE);
//                                more_progress.setVisibility(View.GONE);
//                            } else {
//                                more_layout.setVisibility(View.GONE);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                });
//            }
//
//            @Override
//            public void onError(String tag, final HttpException e) {
//                logger.e(e.getMessage());
//                MyPost.post(new Runnable() {
//                    @Override
//                    public void run() {
////						dismissDialog(dialog);
//                        dismissProgress();
//                        AlertDialogUtil.showDialogByExceptionCode(parent, e);
//                        datas_layout.setVisibility(View.GONE);
//                    }
//                });
//            }
//        }, getClass(), "loadDatas", String.class, double.class, double.class);
    }

    public Observable<LookupAroundDealerResponse> loadDatas(final String cityCode, final double latitude, final double longitude, final int pageNumber, final int pageSize) {
        return Observable.defer(new Func0<Observable<LookupAroundDealerResponse>>() {
            @Override
            public Observable<LookupAroundDealerResponse> call() {
                try {
                    return Observable.just(GsonHelper.fromJson(
                            loadDatasJson(cityCode,latitude,longitude,pageNumber,pageSize),LookupAroundDealerResponse.class ));
                } catch (OnStarException e) {
                    return Observable.error(e);
                }
            }
        });
    }

}
